package com.ouc.eddyAlgorithm.controller;

import com.ouc.common.core.domain.AjaxResult;
import com.ouc.common.entity.NcData;
import com.ouc.common.ncRead.NcDao;
import com.ouc.common.utils.DateUtils;
import com.ouc.common.utils.ExceptionUtil;
import com.ouc.common.utils.MathUtils;
import com.ouc.eddyAlgorithm.domain.*;
import com.ouc.eddyAlgorithm.entity.VGGridData;
import com.ouc.eddyAlgorithm.entity.WGridData;
import com.ouc.eddyAlgorithm.mapper.VgA4b3TrackMapper;
import com.ouc.eddyAlgorithm.mapper.VgAfterTrackMapper;
import com.ouc.eddyAlgorithm.service.FactorAlgorithmService;
import com.ouc.eddyAlgorithm.service.IVgA4b3TrackService;
import com.ouc.eddyAlgorithm.service.OwService;
import com.ouc.eddyAlgorithm.service.VGService;
import com.ouc.visualization.entity.ContourData;
import com.ouc.visualization.entity.FactorCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/eddy")
public class EddyController {


  @Autowired
  FactorAlgorithmService factorAlgorithmService;

  @Autowired
  private OwService owService;

  @Autowired
  private VGService vgService;

  @Autowired
  private NcDao ncDao;

  @Autowired
  private IVgA4b3TrackService iVgA4b3TrackService;

  @Autowired
  private VgA4b3TrackMapper vgA4b3TrackMapper;

  @Autowired
  private VgAfterTrackMapper vgAfterTrackMapper;

//  @Autowired
//  private EddysetVgService eddysetVgService;

//  @Autowired
//  private VGDao vgDao;

  @GetMapping("/w")
  @Deprecated
  public OUCAjaxResult w() throws IOException, InvalidRangeException {
//    File file = new File(regionDir);
    File file = null;
    String fileName = Objects.requireNonNull(file.listFiles(dir -> dir.getPath().endsWith("_uv3z.nc")))[0].getPath();
    ContourData<WGridData> wContourData = owService.getWContourData(fileName);
    return OUCAjaxResult.ok(wContourData);
  }

  /**
   * 原来的vg方法
   */
  @GetMapping("/vg")
  public OUCAjaxResult vg(@RequestParam(value = "a", required = false, defaultValue = "4") Integer a,
                          @RequestParam(value = "b", required = false, defaultValue = "3") Integer b,
                          @RequestParam(value = "fileName", required = false) String fileName,
                          @RequestParam(value = "level", required = false) Integer level,
                          @RequestParam(value = "conditions") String conditions,
                          FactorCondition factorCondition) throws IOException, InvalidRangeException, ParseException {
    try (NetcdfFile ncFile = NetcdfFile.open(fileName)) {
//      eddysetVgService.truncateTable();
      String[] split = conditions.split(",");
      boolean[] constraints = new boolean[split.length];
      for (int i = 0; i < split.length; i++) {
        constraints[i] = Boolean.parseBoolean(split[i]);
      }
      ContourData<VGGridData> vgContourData = vgService.getVGContourData(fileName, a, b, level, constraints, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()},
          new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()});
      VGGridData data = vgContourData.getData();
      List<VgEddy> vgEddyMatrixOfSlice = vgService.getVgEddyMatrixOfSlice(ncFile, a, b, constraints, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()},
          new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()}, factorCondition.getLevel(), 1);
      List<EddysetVg> eddySetList = new ArrayList<>();
      vgEddyMatrixOfSlice
          .forEach(vgEddy -> {
            EddysetVg eddysetVg = new EddysetVg();
            eddysetVg.setEddyId(vgEddy.getEddyId());
            eddysetVg.setEddyType(vgEddy.getType());
            eddysetVg.setEddyDate(DateUtils.parseDate(vgEddy.getDate()));
            eddysetVg.setEddyRadius(vgEddy.getRadius());
            eddysetVg.setRadiusArr(vgEddy.getRadiusArr());
            eddysetVg.setVgEddyI(vgEddy.getI());
            eddysetVg.setEddyLat(vgEddy.getLat());
            eddysetVg.setVgEddyJ(vgEddy.getJ());
            eddysetVg.setEddyLon(vgEddy.getLon());
            eddysetVg.setEddyLevel(vgEddy.getLevel());
            eddysetVg.setEddyDepth(vgEddy.getMeter());
            eddysetVg.setMaxW(vgEddy.getW());
            eddysetVg.setEddyAmp(vgEddy.getEddyAmp());
            eddysetVg.setEddyEke(vgEddy.getEddyEke());
            eddysetVg.setEddyDens(vgEddy.getEddyDens());
            eddySetList.add(eddysetVg);
          });

      /*float[] listLon = data.getListLon();
      float[] listLat = data.getListLat();
      int[] values = data.getValues();
      int k = 0;
      int v = 0;
      for (int i = 0; i < listLon.length; i++) {
        for (int j = 0; j < listLat.length; j++) {
          if (values[i * listLat.length + j] == 1) {
            k++;
          } else if (values[i * listLat.length + j] == 2) {
            v++;
          }
        }
      }
      System.out.println("k = " + k);
      System.out.println("v = " + v);*/
//      eddysetVgService.insertByBach(eddySetList);
//      return OUCAjaxResult.ok(vgContourData);
      return OUCAjaxResult.ok(new Object[]{vgContourData, eddySetList});
    } catch (Exception e) {
      e.printStackTrace();
      return OUCAjaxResult.error("加载失败由于" + ExceptionUtil.getRootErrorMessage(e));
    }
  }

  /**
   * 带异常涡旋检测的vg方法
   */
  @GetMapping("/vgWithAnomalous")
  public OUCAjaxResult vgWithAnomalous(@RequestParam(value = "a", required = false, defaultValue = "4") Integer a,
                                       @RequestParam(value = "b", required = false, defaultValue = "3") Integer b,
                                       @RequestParam(value = "fileName", required = false) String fileName,
                                       @RequestParam(value = "level", required = false) Integer level,
                                       @RequestParam(value = "conditions") String conditions,
                                       FactorCondition factorCondition) throws IOException, InvalidRangeException, ParseException {
    try (NetcdfFile ncFile = NetcdfFile.open(fileName)) {
      String[] split = conditions.split(",");
      boolean[] constraints = new boolean[split.length];
      for (int i = 0; i < split.length; i++) {
        constraints[i] = Boolean.parseBoolean(split[i]);
      }
//      ContourData<VGGridData> vgContourData = vgService.getVGContourData(fileName, a, b, level, constraints, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()},
//          new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()});
//      VGGridData data = vgContourData.getData();

      List<VgEddy> vgEddyMatrixOfSlice = vgService.getVgEddyMatrixOfSlice(ncFile, a, b, constraints, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()},
          new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()}, factorCondition.getLevel(), 1);


      String variableName = "thetao";
      Map<String, NcData> dataMap = ncDao.getNcDataWithLimit(ncFile, variableName, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()}, new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()}, level);
      float[][] temp = dataMap.get(variableName).getData2D();
//            float[] latArr = dataMap.get(ncDao.getVariable(ncFile, "lat").getShortName()).getData1D();
//            float[] lonArr = dataMap.get(ncDao.getVariable(ncFile, "lon").getShortName()).getData1D();
      float[] latArr = dataMap.get("lat").getData1D();
      float[] lonArr = dataMap.get("lon").getData1D();
      float[] dx = {0.5f, -0.5f, 0, 0};
      float[] dy = {0, 0, 0.5f, -0.5f};
      List<EddysetVg> eddySetList = new ArrayList<>();
      for (int tt = 0; tt < vgEddyMatrixOfSlice.size(); tt++) {
        VgEddy vgEddy = vgEddyMatrixOfSlice.get(tt);
        EddysetVg eddysetVg = new EddysetVg();
        eddysetVg.setEddyId(vgEddy.getEddyId());
        eddysetVg.setEddyType(vgEddy.getType());
        eddysetVg.setEddyDate(DateUtils.parseDate(vgEddy.getDate()));
        eddysetVg.setEddyRadius(vgEddy.getRadius());
        eddysetVg.setRadiusArr(vgEddy.getRadiusArr());
        eddysetVg.setVgEddyI(vgEddy.getI());
        eddysetVg.setEddyLat(vgEddy.getLat());
        eddysetVg.setVgEddyJ(vgEddy.getJ());
        eddysetVg.setEddyLon(vgEddy.getLon());
        eddysetVg.setEddyLevel(vgEddy.getLevel());
        eddysetVg.setEddyDepth(vgEddy.getMeter());
        eddysetVg.setMaxW(vgEddy.getW());
        eddysetVg.setEddyAmp(vgEddy.getEddyAmp());
        eddysetVg.setEddyEke(vgEddy.getEddyEke());
        eddysetVg.setEddyDens(vgEddy.getEddyDens());
        eddysetVg.setIsAnomalous(0);
        //判断异常涡
        int numUp = 0, numDown = 0;
        float lon = vgEddy.getLon();
        float lat = vgEddy.getLat();
        int type = vgEddy.getType();
        Float temp0 = MathUtils.getPointFromArr(temp, latArr, lonArr, lat, lon);
        if (!Float.isNaN(temp0)) {
          for (int i = 0; i < 4; i++) {
            Float t = MathUtils.getPointFromArr(temp, latArr, lonArr, lat + dx[i], lon + dy[i]);
            if (!Float.isNaN(t)) {
              if (t > temp0) {
                numUp++;
              }
              if (t < temp0) {
                numDown++;
              }
            }
          }
          if (lat > 0) {
            //北半球 奇数气旋冷涡 ！！！校正：偶数 逆时针 气旋冷涡
            if (((type & 1) == 0 && numDown > 3) || ((type & 1) == 1 && numUp > 3)) {
              eddysetVg.setIsAnomalous(1);
            }
          } else {
            if (((type & 1) == 0 && numUp > 3) || ((type & 1) == 1 && numDown > 3)) {
              eddysetVg.setIsAnomalous(1);
            }
          }
        }
        eddySetList.add(eddysetVg);
      }
//      int num = 0;
//      for (int i = 0; i < eddySetList.size(); i++) {
//        EddysetVg eddysetVg = eddySetList.get(i);
//        if (eddysetVg.getIsAnomalous() == 1) {
//          num++;
//        }
//      }
//      System.out.println(num + "  /  " + eddySetList.size());

      return OUCAjaxResult.ok(eddySetList);
    } catch (Exception e) {
      e.printStackTrace();
      return OUCAjaxResult.error("加载失败由于" + ExceptionUtil.getRootErrorMessage(e));
    }
  }

  /**
   * 带异常涡旋检测的vg方法并存入数据库中
   */
  @GetMapping("/vgWithAnomalousToMysql")
  public OUCAjaxResult vgWithAnomalousToMysql(@RequestParam(value = "a", required = false, defaultValue = "4") Integer a,
                                              @RequestParam(value = "b", required = false, defaultValue = "3") Integer b,
                                              @RequestParam(value = "fileName", required = false) String fileName,
                                              @RequestParam(value = "beginLevel", required = false) Integer beginLevel,
                                              @RequestParam(value = "endLevel", required = false) Integer endLevel,
                                              @RequestParam(value = "conditions") String conditions,
                                              FactorCondition factorCondition) throws IOException, InvalidRangeException, ParseException {
//    String[] fileNameArr = new String[]{
//        "E:\\GlobalData\\2023\\01\\mercatorglorys12v1_gl12_mean_20230101_R20230104.nc",
//
//    };

    try {
      int eddyStardId = 1;
      String resultString = new String();
//      for (int fileI = 0; fileI < fileNameArr.length; fileI++) {
//        String fileName = fileNameArr[fileI];
      NetcdfFile ncFile = NetcdfFile.open(fileName);
      List<EddysetVg> eddyResult = new ArrayList<>();

      for (int level = beginLevel; level <= endLevel; level++) {

        String[] fileNameSplit = fileName.split("_");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = dateFormat.parse(fileNameSplit[3]);
        String[] split = conditions.split(",");
        boolean[] constraints = new boolean[split.length];
        for (int i = 0; i < split.length; i++) {
          constraints[i] = Boolean.parseBoolean(split[i]);
        }

        factorCondition.setLevel(level);
        List<VgEddy> vgEddyMatrixOfSlice = vgService.getVgEddyMatrixOfSlice(ncFile, a, b, constraints, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()},
            new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()}, level, eddyStardId);
        eddyStardId += vgEddyMatrixOfSlice.size();

        String variableName = "thetao";
        Map<String, NcData> dataMap = ncDao.getNcDataWithLimit(ncFile, variableName, new Float[]{factorCondition.getStartLon(), factorCondition.getEndLon()}, new Float[]{factorCondition.getStartLat(), factorCondition.getEndLat()}, level);
        float[][] temp = dataMap.get(variableName).getData2D();
        float[] latArr = dataMap.get("lat").getData1D();
        float[] lonArr = dataMap.get("lon").getData1D();
        float[] dx = {0.5f, -0.5f, 0, 0};
        float[] dy = {0, 0, 0.5f, -0.5f};
        List<EddysetVg> eddySetList = new ArrayList<>();
        float[] depthArr = dataMap.get("depth").getData1D();
        for (int tt = 0; tt < vgEddyMatrixOfSlice.size(); tt++) {
          VgEddy vgEddy = vgEddyMatrixOfSlice.get(tt);
          EddysetVg eddysetVg = new EddysetVg();
          eddysetVg.setEddyId(vgEddy.getEddyId());
          eddysetVg.setEddyType(vgEddy.getType());
          eddysetVg.setEddyDate(DateUtils.parseDate(vgEddy.getDate()));
          eddysetVg.setEddyRadius(vgEddy.getRadius());
          eddysetVg.setRadiusArr(vgEddy.getRadiusArr());
          eddysetVg.setVgEddyI(vgEddy.getI());
          eddysetVg.setEddyLat(vgEddy.getLat());
          eddysetVg.setVgEddyJ(vgEddy.getJ());
          eddysetVg.setEddyLon(vgEddy.getLon());
          eddysetVg.setEddyLevel(vgEddy.getLevel());
          eddysetVg.setEddyDepth(vgEddy.getMeter());
          eddysetVg.setMaxW(vgEddy.getW());
          eddysetVg.setEddyAmp(vgEddy.getEddyAmp());
          eddysetVg.setEddyEke(vgEddy.getEddyEke());
          eddysetVg.setEddyDens(vgEddy.getEddyDens());
          eddysetVg.setIsAnomalous(0);
          //判断异常涡
          int numUp = 0, numDown = 0;
          float lon = vgEddy.getLon();
          float lat = vgEddy.getLat();
          int type = vgEddy.getType();
          Float temp0 = MathUtils.getPointFromArr(temp, latArr, lonArr, lat, lon);
          if (!Float.isNaN(temp0)) {
            for (int i = 0; i < 4; i++) {
              Float t = MathUtils.getPointFromArr(temp, latArr, lonArr, lat + dx[i], lon + dy[i]);
              if (!Float.isNaN(t)) {
                if (t > temp0) {
                  numUp++;
                }
                if (t < temp0) {
                  numDown++;
                }
              }
            }
            eddysetVg.setIsAnomalous(0);
            if (lat > 0) {
              //北半球 奇数气旋冷涡 ！！！校正：偶数 逆时针 气旋冷涡
              if (((type & 1) == 0 && numDown > 3) || ((type & 1) == 1 && numUp > 3)) {
                eddysetVg.setIsAnomalous(1);
              }
            } else {
              if (((type & 1) == 0 && numUp > 3) || ((type & 1) == 1 && numDown > 3)) {
                eddysetVg.setIsAnomalous(1);
              }
            }
          }
          eddyResult.add(eddysetVg);
          VgA4b3Track vgA4b3Track = new VgA4b3Track();
          vgA4b3Track.setDate(eddysetVg.getEddyDate());
          vgA4b3Track.setType(eddysetVg.getEddyType());
          vgA4b3Track.setRadius(Double.valueOf(eddysetVg.getEddyRadius()));
          vgA4b3Track.setRadiusArr(eddysetVg.getRadiusArr());
          vgA4b3Track.setI(eddysetVg.getVgEddyI());
          vgA4b3Track.setLat(Double.valueOf(eddysetVg.getEddyLat()));
          vgA4b3Track.setJ(eddysetVg.getVgEddyJ());
          vgA4b3Track.setLon(Double.valueOf(eddysetVg.getEddyLon()));
          vgA4b3Track.setW(eddysetVg.getMaxW().doubleValue());
          vgA4b3Track.setIsAnomalous(eddysetVg.getIsAnomalous());
          vgA4b3Track.setLevel(level);
          vgA4b3Track.setMeter((double) depthArr[level]);
          vgA4b3Track.setDate(date);
          iVgA4b3TrackService.insertVgA4b3Track(vgA4b3Track);
        }
        System.out.println("识别并插入涡旋，时间：" + date + "；层级：" + level + "；数量：" + vgEddyMatrixOfSlice.size());
        resultString += "识别并插入涡旋，时间：" + date + "；层级：" + level + "；数量：" + vgEddyMatrixOfSlice.size();
//        }

        System.out.println("识别涡旋并插入数据数目 = " + eddyResult.size());
      }
      return OUCAjaxResult.ok("识别涡旋并插入数据数目 = " + (eddyStardId - 1) + "。 " + resultString);
    } catch (Exception e) {
      e.printStackTrace();
      return OUCAjaxResult.error("加载失败由于" + ExceptionUtil.getRootErrorMessage(e));
    }
  }
//  E:\GlobalData\2023\01\mercatorglorys12v1_gl12_mean_20230101_R20230104.nc

  /**
   * 预报数据 vg识别，入库，跟踪
   *
   * @param a
   * @param b
   * @param beginLevel
   * @param endLevel
   * @param conditions
   * @param index
   * @return
   * @throws IOException
   * @throws InvalidRangeException
   * @throws ParseException
   */
  @PostMapping("/vgByForecast")
  public OUCAjaxResult vgByForecast(@RequestParam(value = "a", required = false, defaultValue = "4") Integer a,
                                    @RequestParam(value = "b", required = false, defaultValue = "3") Integer b,
//                                              @RequestParam(value = "fileName", required = false) String fileName,
                                    @RequestParam(value = "beginLevel", required = false, defaultValue = "0") Integer beginLevel,
                                    @RequestParam(value = "endLevel", required = false, defaultValue = "0") Integer endLevel,
                                    @RequestParam(value = "conditions") String conditions,
                                    @RequestParam(value = "index", required = false, defaultValue = "7") Integer index) {

    Date today = DateUtils.parseDate(DateUtils.getDate());
    //删除今天往后的涡旋数据
    int deleteNum = iVgA4b3TrackService.deleteTodayEddy(today);
    System.out.println("删除今天及往后的涡旋数量：" + deleteNum);

    String todayString = DateUtils.parseDateToStr("yyyyMMdd", today);
    String resultString = new String();
    int eddyStardId = 1;
    try {
      for (int daysI = 0; daysI < index.intValue(); daysI++) {
        Date day = DateUtils.addDays(today, daysI);
        String time = DateUtils.parseDateToStr("yyyyMMdd", day);
        String fileName = "D:\\mydatabase\\forecastdata\\" + todayString + "\\" + time + "_cur.nc";
        NetcdfFile ncFile = NetcdfFile.open(fileName);
        for (int level = beginLevel; level <= endLevel; level++) {
          String[] split = conditions.split(",");
          boolean[] constraints = new boolean[split.length];
          for (int i = 0; i < split.length; i++) {
            constraints[i] = Boolean.parseBoolean(split[i]);
          }

          List<VgEddy> vgEddyMatrixOfSlice = vgService.getVgEddyMatrixOfSlice(ncFile, a, b, constraints, new Float[]{-180.0f, 180.0f}, new Float[]{-80.0f, 90.0f}, level, eddyStardId);
          eddyStardId += vgEddyMatrixOfSlice.size();

          for (int tt = 0; tt < vgEddyMatrixOfSlice.size(); tt++) {
            VgEddy vgEddy = vgEddyMatrixOfSlice.get(tt);

            VgA4b3Track vgA4b3Track = new VgA4b3Track();
            vgA4b3Track.setType(vgEddy.getType());
            vgA4b3Track.setRadius(Double.valueOf(vgEddy.getRadius()));
            vgA4b3Track.setRadiusArr(vgEddy.getRadiusArr());
            vgA4b3Track.setI(vgEddy.getI());
            vgA4b3Track.setLat(Double.valueOf(vgEddy.getLat()));
            vgA4b3Track.setJ(vgEddy.getJ());
            vgA4b3Track.setLon(Double.valueOf(vgEddy.getLon()));
            vgA4b3Track.setW((double) vgEddy.getW());
            vgA4b3Track.setLevel(level);
            vgA4b3Track.setDate(day);
            iVgA4b3TrackService.insertVgA4b3Track(vgA4b3Track);
          }

          System.out.println("识别并插入涡旋，时间：" + day + "；层级：" + level + "；数量：" + vgEddyMatrixOfSlice.size());
          resultString += "识别并插入涡旋，时间：" + day + "；层级：" + level + "；数量：" + vgEddyMatrixOfSlice.size();
        }
      }

      //涡旋跟踪
      String startTime = DateUtils.parseDateToStr("yyyy-MM-dd", today);
      Date endDate = DateUtils.addDays(today, index.intValue());
      String endTime = DateUtils.parseDateToStr("yyyy-MM-dd", endDate);

      int num = iVgA4b3TrackService.vgEddyTrack(startTime, endTime, -80.0f, 90.0f, -180.0f, 180.0f, 3, 5, 0.3f);
      System.out.println("更新涡旋数目num = " + num);

      return OUCAjaxResult.ok("识别涡旋并插入数据数目 = " + (eddyStardId - 1) + "。 " + resultString);
    } catch (Exception e) {
      e.printStackTrace();
      return OUCAjaxResult.error("加载失败由于" + ExceptionUtil.getRootErrorMessage(e));
    }
  }

  /**
   * 预报数据，涡旋识别结果 ——> json
   *
   * @param index 7天
   * @return
   * @throws ParseException
   */
  @PostMapping("vgToJson")
  public AjaxResult vgToJson(@RequestParam(value = "index", required = false, defaultValue = "7") Integer index) throws ParseException {
    Date today = DateUtils.parseDate(DateUtils.getDate());
    String todayString = DateUtils.parseDateToStr("yyyyMMdd", today);
    for (int i = 0; i < index.intValue(); i++) {
      Date day = DateUtils.addDays(today, i);
      String time = DateUtils.parseDateToStr("yyyyMMdd", day);
      iVgA4b3TrackService.vgToJson(time);

    }

    return AjaxResult.success("已生成");
  }

  @PostMapping("vgTrackToJson")
  public AjaxResult vgTrackToJson(@RequestParam(value = "track") Integer track) {

    return AjaxResult.success(iVgA4b3TrackService.vgTrackToJson(track));
  }


  /**
   * 跟踪校准识别
   */
  @GetMapping("/vgAfterTrack")
  public OUCAjaxResult vgAfterTrack(@RequestParam(value = "startTime") String startTime,
                                    @RequestParam(value = "endTime") String endTime,
                                    @RequestParam(value = "t") int t) throws ParseException {
    int eddyNum = 0;
    Calendar calendar = new GregorianCalendar();
    String formatType = "yyyy-MM-dd";
    SimpleDateFormat formatter = new SimpleDateFormat(formatType);
    Date startData = formatter.parse(startTime);
    Date endData = formatter.parse(endTime);
    Date date = startData;
    while (date.compareTo(endData) <= 0) {
      VgA4b3Track vgA4b3Track = new VgA4b3Track();
      Map<String, Object> params = new HashMap<>();
      params.put("beginDate", formatter.format(date));
      params.put("endDate", formatter.format(date));
      params.put("t", t);

      vgA4b3Track.setParams(params);
      List<VgA4b3Track> vgA4b3TrackList = vgA4b3TrackMapper.selectVgA4b3TrackByDate(vgA4b3Track);
      for (int i = 0; i < vgA4b3TrackList.size(); i++) {
        int track = vgA4b3TrackList.get(i).getTrack();
        VgA4b3Track vgA4b3Track1 = new VgA4b3Track();
        Map<String, Object> params1 = new HashMap<>();
        params1.put("beginDate", formatter.format(date));
        params1.put("endDate", formatter.format(date));
        vgA4b3Track1.setTrack(track);
        vgA4b3Track1.setParams(params1);
        List<VgA4b3Track> vgA4b3Tracks = vgA4b3TrackMapper.selectVgA4b3TrackList(vgA4b3Track1);
        int beginLevel = vgA4b3Tracks.get(0).getLevel();
        int endLevel = vgA4b3Tracks.get(0).getLevel();
        int isAnomalous = 0;
        double radius = 0.0;
        int di = 0, dj = 0;
        double lon = 0, lat = 0;
        double w = 0;

        for (int j = 0; j < vgA4b3Tracks.size(); j++) {
          if (vgA4b3Tracks.get(j).getLevel() < beginLevel) {
            beginLevel = vgA4b3Tracks.get(j).getLevel();
          }
          if (vgA4b3Tracks.get(j).getLevel() > endLevel) {
            endLevel = vgA4b3Tracks.get(j).getLevel();
          }
          isAnomalous += vgA4b3Tracks.get(j).getIsAnomalous();
          radius += vgA4b3Tracks.get(j).getRadius();
          di += vgA4b3Tracks.get(j).getI();
          dj += vgA4b3Tracks.get(j).getJ();
          lon += vgA4b3Tracks.get(j).getLon();
          lat += vgA4b3Tracks.get(j).getLat();
          if (vgA4b3Tracks.get(j).getW() > w) {
            w = vgA4b3Tracks.get(j).getW();
          }

        }

        VgAfterTrack vgAfterTrack = new VgAfterTrack();
        vgAfterTrack.setTrack(track);
        vgAfterTrack.setBeginLevel(beginLevel);
        vgAfterTrack.setEndLevel(endLevel);
        if (isAnomalous > 1) {
          isAnomalous = 1;
        }
        vgAfterTrack.setIsAnomalous(isAnomalous);
        vgAfterTrack.setRadius(radius / vgA4b3Tracks.size());
        vgAfterTrack.setDate(date);
        vgAfterTrack.setType(vgA4b3Tracks.get(0).getType());
        vgAfterTrack.setI(di / vgA4b3Tracks.size());
        vgAfterTrack.setJ(dj / vgA4b3Tracks.size());
        vgAfterTrack.setLon(lon / vgA4b3Tracks.size());
        vgAfterTrack.setLat(lat / vgA4b3Tracks.size());
        vgAfterTrack.setW(w);

        vgAfterTrackMapper.insertVgAfterTrack(vgAfterTrack);
        eddyNum++;
      }

      System.out.println("时间： " + date + "插入中尺度涡旋数目：" + eddyNum);
      calendar.setTime(date);
      calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
      date = calendar.getTime(); //这个时间就是日期往后推一天的结果
    }

    return OUCAjaxResult.ok("插入中尺度涡旋数目：" + eddyNum);
  }


}
